package com.example.userp.app.myapplication.InnerPrient.utils;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.RemoteException;
import android.util.Log;
import android.widget.Toast;

import com.example.userp.app.myapplication.R;
import com.sunmi.peripheral.printer.ICallback;
import com.sunmi.peripheral.printer.InnerPrinterCallback;
import com.sunmi.peripheral.printer.InnerPrinterException;
import com.sunmi.peripheral.printer.InnerPrinterManager;
import com.sunmi.peripheral.printer.SunmiPrinterService;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;


public class AidlUtil {
    private static final String SERVICE＿PACKAGE = "woyou.aidlservice.jiuiv5";
    private static final String SERVICE＿ACTION = "woyou.aidlservice.jiuiv5.ImService";

    private static AidlUtil mAidlUtil = new AidlUtil();
    private Context context;
    private SunmiPrinterService mService;
    private InnerPrinterCallback mInnerPrinterCallback;

    private AidlUtil() {
    }

    public static AidlUtil getInstance() {
        return mAidlUtil;
    }

    /**
     * 连接服务
     *
     * @param context context
     */
    public void connectPrinterService(Context context) throws InnerPrinterException {
        this.context = context.getApplicationContext();

        //当服务异常断开后，会回调此⽅法 } }
        mInnerPrinterCallback = new InnerPrinterCallback() {
            @Override
            protected void onConnected(SunmiPrinterService service) {
                Log.e("tag", "打印启动 onConnected: ");
                mService = service;
            }

            @Override
            protected void onDisconnected() {
                //当服务异常断开后，会回调此⽅法 } }
                Log.e("tag", "服务异常 onDisconnected: ");
            }
        };
        InnerPrinterManager.getInstance().bindService(context, mInnerPrinterCallback);
    }

    /**
     * 断开服务
     *
     * @param context context
     */
    public void disconnectPrinterService(Context context) {
        if (mService != null) {
            try {
                InnerPrinterManager.getInstance().unBindService(context, mInnerPrinterCallback);
            } catch (InnerPrinterException e) {
                e.printStackTrace();
            }
            mService = null;
        }
    }

    public boolean isConnect() {
        return mService != null;
    }


    public ICallback generateCB(final PrinterCallback printerCallback) {
        return new ICallback.Stub() {


            @Override
            public void onRunResult(boolean isSuccess) throws RemoteException {

            }

            @Override
            public void onReturnString(String result) throws RemoteException {
                printerCallback.onReturnString(result);
            }

            @Override
            public void onRaiseException(int code, String msg) throws RemoteException {

            }

            @Override
            public void onPrintResult(int code, String msg) throws RemoteException {

            }
        };
    }

    /**
     * 设置打印浓度
     */
    private int[] darkness = new int[]{0x0600, 0x0500, 0x0400, 0x0300, 0x0200, 0x0100, 0,
            0xffff, 0xfeff, 0xfdff, 0xfcff, 0xfbff, 0xfaff};

    public void setDarkness(int index) {
        if (mService == null) {
            Toast.makeText(context, R.string.toast_2, Toast.LENGTH_LONG).show();
            return;
        }

        int k = darkness[index];
        try {
            mService.sendRAWData(ESCUtil.setPrinterDarkness(k), null);
            mService.printerSelfChecking(null);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    /**
     * 取得打印机系统信息，放在list中
     *
     * @return list
     */
    public List<String> getPrinterInfo(PrinterCallback printerCallback1, PrinterCallback printerCallback2) {
        if (mService == null) {
            Toast.makeText(context, R.string.toast_2, Toast.LENGTH_LONG).show();
            return null;
        }

        List<String> info = new ArrayList<>();
        try {
            mService.getPrintedLength(generateCB(printerCallback1));
            mService.getPrinterFactory(generateCB(printerCallback2));
            info.add(mService.getPrinterSerialNo());
            info.add(mService.getPrinterModal());
            info.add(mService.getPrinterVersion());
            info.add(printerCallback1.getResult());
            info.add(printerCallback2.getResult());
            //info.add(mService.getServiceVersion());
            PackageManager packageManager = context.getPackageManager();
            try {
                PackageInfo packageInfo = packageManager.getPackageInfo(SERVICE＿PACKAGE, 0);
                if (packageInfo != null) {
                    info.add(packageInfo.versionName);
                    info.add(packageInfo.versionCode + "");
                } else {
                    info.add("");
                    info.add("");
                }
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }

        } catch (RemoteException e) {
            e.printStackTrace();
        }
        return info;
    }

    /**
     * 初始化打印机
     */
    public void initPrinter() {
        if (mService == null) {
            Toast.makeText(context, R.string.toast_2, Toast.LENGTH_LONG).show();
            return;
        }

        try {
            mService.printerInit(null);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    /**
     * 打印机 规格
     */
    public int getPrinterPaper() {
        if (mService == null) {
            Toast.makeText(context, R.string.toast_2, Toast.LENGTH_LONG).show();
            return 0;
        }

        try {
            int c = mService.getPrinterPaper();
            return c;
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 打印二维码
     */
    public void printQr(String data, int modulesize, int errorlevel) {
        if (mService == null) {
            Toast.makeText(context, R.string.toast_2, Toast.LENGTH_LONG).show();
            return;
        }

        try {
            mService.setAlignment(1, null);
            mService.printQRCode(data, modulesize, errorlevel, null);
            mService.lineWrap(3, null);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    /**
     * 打印条形码
     */
    public void printBarCode(String data, int symbology, int height, int width, int textposition) {
        if (mService == null) {
            Toast.makeText(context, R.string.toast_2, Toast.LENGTH_LONG).show();
            return;
        }


        try {
            mService.printBarCode(data, symbology, height, width, textposition, null);
            mService.lineWrap(3, null);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    /**
     * 打印文字
     *
     * @param content
     * @param alignment   对齐模式  0!居左 , 1!居中, 2!居右
     * @param size        字体大小
     * @param isBold      加粗
     * @param isUnderLine
     */
    public void printText(String content, int alignment, float size, boolean isBold, boolean isUnderLine) {
        if (mService == null) {
            Toast.makeText(context, R.string.toast_2, Toast.LENGTH_LONG).show();
            return;
        }

        try {
            if (isBold) {
                mService.sendRAWData(ESCUtil.boldOn(), null);
            } else {
                mService.sendRAWData(ESCUtil.boldOff(), null);
            }

            mService.setAlignment(alignment, null);

            if (isUnderLine) {
                mService.sendRAWData(ESCUtil.underlineWithOneDotWidthOn(), null);
            } else {
                mService.sendRAWData(ESCUtil.underlineOff(), null);
            }

            mService.printTextWithFont(content, null, size, null);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    /**
     * 打印文字的设置
     *
     * @param alignment   对齐模式  0!居左 , 1!居中, 2!居右
     * @param size        字体大小
     * @param isBold      加粗
     * @param isUnderLine
     */
    public void TextSetting(int alignment, float size, boolean isBold, boolean isUnderLine) {
        if (mService == null) {
            Toast.makeText(context, R.string.toast_2, Toast.LENGTH_LONG).show();
            return;
        }

        try {
            if (isBold) {
                mService.sendRAWData(ESCUtil.boldOn(), null);
            } else {
                mService.sendRAWData(ESCUtil.boldOff(), null);
            }

            mService.setAlignment(alignment, null);

            if (isUnderLine) {
                mService.sendRAWData(ESCUtil.underlineWithOneDotWidthOn(), null);
            } else {
                mService.sendRAWData(ESCUtil.underlineOff(), null);
            }
            mService.setFontSize(size, null);

        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    /*
     *打印图片
     */
    public void printBitmap(Bitmap bitmap) {
        if (mService == null) {
            Toast.makeText(context, R.string.toast_2, Toast.LENGTH_LONG).show();
            return;
        }

        try {
            mService.setAlignment(1, null);
            mService.printBitmap(bitmap, null);
            mService.lineWrap(3, null);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }


    /**
     * 打印图片和文字按照指定排列顺序
     */
    public void printBitmap(Bitmap bitmap, int orientation) {
        if (mService == null) {
            Toast.makeText(context, "服务已断开！", Toast.LENGTH_LONG).show();
            return;
        }

        try {
            if (orientation == 0) {
                mService.printBitmap(bitmap, null);
                mService.printText("横向排列\n", null);
                mService.printBitmap(bitmap, null);
                mService.printText("横向排列\n", null);
            } else {
                mService.printBitmap(bitmap, null);
                mService.printText("\n纵向排列\n", null);
                mService.printBitmap(bitmap, null);
                mService.printText("\n纵向排列\n", null);
            }
            mService.lineWrap(3, null);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }


    /**
     * 打印单行表格
     */
    public void printLineTable(String[] colsTextArr, int[] colsWidthArr, int[] colsAlign, ICallback callback) {
        if (mService == null) {
            Toast.makeText(context, R.string.toast_2, Toast.LENGTH_LONG).show();
            return;
        }

        try {
            mService.printColumnsString(colsTextArr, colsWidthArr, colsAlign, null);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    /*
     * 空打三行！
     */
    public void print3Line() {
        if (mService == null) {
            Toast.makeText(context, R.string.toast_2, Toast.LENGTH_LONG).show();
            return;
        }

        try {
            mService.lineWrap(3, null);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }


    /**
     * 空 走纸
     *
     * @param n 行
     */
    public void printNLine(int n) {
        if (mService == null) {
            Toast.makeText(context, R.string.toast_2, Toast.LENGTH_LONG).show();
            return;
        }

        try {
            mService.lineWrap(n, null);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    /**
     * 打印ESC/POS格式指令
     *
     * @param data
     */
    public void sendRawData(byte[] data) {
        if (mService == null) {
            Toast.makeText(context, R.string.toast_2, Toast.LENGTH_LONG).show();
            return;
        }

        try {
            mService.sendRAWData(data, null);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    public void sendRawDatabyBuffer(byte[] data, ICallback iCallback) {
        if (mService == null) {
            Toast.makeText(context, R.string.toast_2, Toast.LENGTH_LONG).show();
            return;
        }

        try {
            mService.enterPrinterBuffer(true);
            mService.sendRAWData(data, iCallback);
            mService.exitPrinterBufferWithCallback(true, iCallback);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
}
